<template>
	<view class="page">
		<template v-if="loadMoreStatus!=='loading'">
			<template v-if="parentObj.groupNotice">
				<view class="page-head">群公告: {{parentObj.groupNotice||''}}</view>
				<u-line></u-line>
			</template>

			<!-- 父级群聊 -->
			<quick-group-list :list="[parentObj]" :openId="openId" padding="0" radius="0" forceDisplay @detail="itemToDetail"
				@detailMore="parentMoreHandle"></quick-group-list>
		</template>

		<view class="module">
			<view class="module-title">
				<text>小组群聊</text>
				<u-button v-if="parentObj.openId===openId" plain color="#276AEE" throttleTime="500"
					:customStyle="{width:'120rpx',height:'56rpx',margin:'0',fontSize:'28rpx'}" @click="addHandle">创建</u-button>
			</view>

			<!-- 子级群聊列表 -->
			<quick-group-list :list="items" :openId="openId" forceDisplay @detail="itemToDetail"
				@detailMore="childMoreHandle"></quick-group-list>

			<template v-if="loadMoreStatus!=='loading'&&!items.length">
				<u-empty marginTop="32rpx" width="240rpx" height="240rpx" text="暂无小组" textSize="28rpx" textColor="#86909C"
					icon="https://file.casugn.com/storecompcard/temp/Add Comment@2x_1681113604168.png"></u-empty>
			</template>

			<template v-if="loadMoreStatus==='loading'">
				<u-loadmore height="100" fontSize="28rpx" iconSize="34rpx" :status="loadMoreStatus" @loadmore="scrolltolower" />
			</template>
		</view>

		<!-- 新增/编辑弹窗 -->
		<quick-group-popup ref="QuickGroup" :isGroup="false" @refresh="refresherrefresh"></quick-group-popup>

		<!-- 父级更多操作弹窗 -->
		<quick-group-more ref="ParentMore" title="请选择操作" :list="parentMoreList"
			@itemClick="parentMoreItemClick"></quick-group-more>

		<!-- 子集更多操作弹窗 -->
		<quick-group-more ref="ChildMore" title="请选择操作" :list="childMoreList"
			@itemClick="childMoreItemClick"></quick-group-more>

		<!-- 群组人员列表 -->
		<quick-group-add-member ref="GroupMember"></quick-group-add-member>

		<!-- 删除群组成员/删除小组成员 -->
		<quick-group-remove-member ref="RemoveMember"></quick-group-remove-member>

		<!-- 群二维码 -->
		<quick-group-qrcode ref="GroupQrcode"></quick-group-qrcode>
	</view>
</template>

<script>
	import { mapGetters } from 'vuex'
	import QuickGroupList from '../components/quick-group-list/quick-group-list.vue'
	import QuickGroupPopup from '../components/quick-group-popup/quick-group-popup.vue'
	import QuickGroupMore from '../components/quick-group-more/quick-group-more.vue'
	import QuickGroupQrcode from '../components/quick-group-qrcode/quick-group-qrcode.vue'
	import QuickGroupAddMember from './components/quick-group-add-member.vue'
	import QuickGroupRemoveMember from '../components/quick-group-remove-member/quick-group-remove-member.vue'

	export default {
		components: {
			QuickGroupList,
			QuickGroupPopup,
			QuickGroupMore,
			QuickGroupQrcode,
			QuickGroupAddMember,
			QuickGroupRemoveMember,
		},
		data() {
			return {
				parentMoreList: [{
						name: '分享群聊',
						openType: 'share',
						show: true,
					},
					{
						name: '群二维码',
						value: 'qrcode',
						show: true,
					},
					{
						name: '人员管理',
						value: 'person',
						show: true,
					},
					{
						name: '退出群聊',
						value: 'exit',
						show: true,
					},
				],
				childMoreList: [{
						name: '添加成员',
						value: 'add',
						show: true,
					},
					{
						name: '管理成员',
						value: 'manage',
						show: true,
					},
					{
						name: '编辑小组',
						value: 'edit',
						show: true,
					},
					{
						name: '解散小组',
						value: 'delete',
						show: true,
					},
					{
						name: '退出小组',
						value: 'exit',
						show: true,
					},
				],

				parentObj: {},

				items: [],
				pageNo: 1,
				pageSize: 10,
				loadMoreStatus: 'loading', //loading / nomore / loadmore
			}
		},
		computed: {
			...mapGetters(['quickGroupUserInfo', 'openId']),
		},
		onLoad(option) {
			this.parentObj.id = option.id
		},
		onShow() {
			this.loadMoreStatus = 'loading'
			this.getDBData()
		},
		onPullDownRefresh() {
			this.refresherrefresh()
			uni.stopPullDownRefresh()
		},
		onShareAppMessage(res) {
			// 防止分享人是快速建群的分享进入,没有quickGroupUserInfo
			return {
				title: (this.quickGroupUserInfo.name || '') + '邀请您加入群聊',
				path: '/pagesCard/joinQuickGroup/joinQuickGroup?id=' + this.parentObj.id
			}
		},
		methods: {
			// 创建 聊天室 进入群聊
			itemToDetail({ item }) {
				uni.navigateTo({
					url: `/pagesCard/quickGroupChatRoom/quickGroupChatRoom?groupId=${item.id}&roomId=${item.roomId}&chatTitle=${item.groupName}&ownerOpenId=${item.openId}`
				})
			},
			addHandle() {
				this.$refs.QuickGroup.add({ parentId: this.parentObj.id })
			},
			parentMoreHandle() {
				this.$refs.ParentMore.show()
				// 人员管理
				this.$set(this.parentMoreList[2], 'show', this.openId === this.parentObj.openId)
				// 退出群聊
				this.$set(this.parentMoreList[3], 'show', this.openId !== this.parentObj.openId)
			},
			parentMoreItemClick({ value, index }) {
				switch (value) {
					case 'share':
						// open-type 不进入此方法
						break;
					case 'qrcode':
						this.$refs.GroupQrcode.show({
							page: 'pagesCard/joinQuickGroup/joinQuickGroup',
							id: this.parentObj.id
						})
						break;
					case 'person':
						this.$refs.RemoveMember.show({
							title: '管理群聊成员',
							groupId: this.parentObj.id,
						})
						break;
					case 'exit':
						this.parentExitHandle()
						break;
				}
			},
			// 从父级群聊离开
			parentExitHandle() {
				uni.showModal({
					content: `确认退出群聊[${this.parentObj.groupName}]?`,
					success: async (res) => {
						if (res.confirm) {
							//主动退出群聊
							let res = await this.$api.leaveQuickGroup(this.parentObj.id, this.openId, )
							if (res.success) {
								uni.showToast({ title: '退出群聊成功', icon: 'none' });

								setTimeout(() => {
									let pages = getCurrentPages() // 获取当前页面栈
									if (pages.length > 1) {
										uni.navigateBack()
									} else {
										uni.reLaunch({
											url: '/pages/card/card'
										})
									}
								}, 1000)
							} else {
								uni.showToast({ title: res.message || '退出群聊失败!', icon: 'none' });
							}
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				})
			},
			//显示弹窗
			childMoreHandle({ item, index }) {
				this.$refs.ChildMore.show(item, index)
				// 添加小组成员
				this.$set(this.childMoreList[0], 'show', item.openId === this.openId)
				// 管理小组人员
				this.$set(this.childMoreList[1], 'show', item.openId === this.openId)
				// 编辑小组
				this.$set(this.childMoreList[2], 'show', item.openId === this.openId)
				// 解散小组
				this.$set(this.childMoreList[3], 'show', item.openId === this.openId)
				// 离开小组
				this.$set(this.childMoreList[4], 'show', item.openId !== this.openId)
			},
			childMoreItemClick({ value, index, data, dataIndex }) {
				console.log(value, index, data, dataIndex);
				switch (value) {
					case 'add':
						this.childAddHandle(data, dataIndex)
						break;
					case 'manage':
						this.$refs.RemoveMember.show({
							title: '管理小组成员',
							groupId: data.id,
						})
						break;
					case 'edit':
						this.$refs.QuickGroup.edit(data)
						break;
					case 'delete':
						this.childDeleteHandle(data, dataIndex)
						break;
					case 'exit':
						this.childExitHandle(data, dataIndex)
						break;
				}
			},
			//显示群组人员
			childAddHandle(item, index) {
				//使用新接口查询 群组人员列表 ,已经加入该小组的成员会过滤掉 
				this.$refs.GroupMember.show(item)
			},
			childDeleteHandle(item, index) {
				const that = this
				uni.showModal({
					content: `确认删除小组[${item.groupName}]?`,
					success: async (res) => {
						if (res.confirm) {
							let res = await this.$api.delQuickGruopListById(item.id)
							if (res.success) {
								uni.showToast({ title: '删除成功！', icon: 'none' });
								that.items.splice(index, 1)
							} else {
								uni.showToast({ title: res.message || '删除失败！', icon: 'none' });
							}
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				})
			},
			//主动退出群聊
			childExitHandle(item, index) {
				const that = this
				uni.showModal({
					content: `确认退出小组[${item.groupName}]?`,
					success: async (res) => {
						if (res.confirm) {
							let res = await this.$api.leaveQuickGroup(item.id, this.openId)
							if (res.success) {
								uni.showToast({ title: res.message || '退出成功！', icon: 'none' });
								that.items.splice(index, 1)
							} else {
								uni.showToast({ title: res.message || '退出失败！', icon: 'none' });
							}
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				})
			},
			async getDBData() {
				let params = {
					openId: this.openId,
					groupId: this.parentObj.id
				}
				let res = await this.$api.findMyGroup(params)
				if (res.success) {
					this.items = res.result.filter(item => item.parentId)
					console.log('小组列表：', this.items);

					let tFilter = res.result.filter(item => item.id === this.parentObj.id)
					if (tFilter.length) {
						this.parentObj = tFilter[0]
					}

					this.loadMoreStatus = 'nomore'
				} else {
					this.loadMoreStatus = 'nomore'
				}
			},
			refresherrefresh() {
				this.loadMoreStatus = 'loading'
				this.items = []
				this.pageNo = 1
				setTimeout(async () => {
					await this.getDBData()
				}, 500)
			},
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #F7F8FA;
	}

	.page {
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
	}

	.page-head {
		padding: 32rpx;
		font-weight: 600;
		font-size: 30rpx;
		text-shadow: 2rpx 3rpx 1rpx #ccc;
		background-color: #fff;
	}

	.module {
		margin-top: 24rpx;

		.module-title {
			padding: 20rpx 32rpx;
			font-size: 32rpx;
			font-weight: 600;
			color: #1D2129;
			line-height: 44rpx;

			display: flex;
			justify-content: space-between;
			align-items: center;
		}
	}
</style>